package com.xydtech.common.wechat.config;

import com.xydtech.common.wechat.domin.GetWechatQRCodeResponse;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;

/**
 * 微信回传信息转换器（处理RestTemplate出错问题）
 *
 * @author Daniel
 * @date 2022/2/9 10:45
 */
public class WechatMiniProgramConfig {

    public static class WechatMiniProgramRepoConverter extends AbstractHttpMessageConverter<GetWechatQRCodeResponse> {

        public WechatMiniProgramRepoConverter() {
            super.setSupportedMediaTypes(Collections.singletonList(MediaType.IMAGE_JPEG));
        }

        @Override
        protected boolean supports(Class<?> clazz) {
            return GetWechatQRCodeResponse.class == clazz;
        }

        @Override
        protected GetWechatQRCodeResponse readInternal(Class<? extends GetWechatQRCodeResponse> clazz,
                                                          HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
            long contentLen = inputMessage.getHeaders().getContentLength();
            ByteArrayOutputStream bos = new ByteArrayOutputStream(contentLen>=0?(int)contentLen:StreamUtils.BUFFER_SIZE);
            StreamUtils.copy(inputMessage.getBody(), bos);
            bos.toByteArray();
            GetWechatQRCodeResponse wechatQRCodeResponse = new GetWechatQRCodeResponse();
            wechatQRCodeResponse.setBuffer(bos.toByteArray());
            wechatQRCodeResponse.setErrcode(0);
            wechatQRCodeResponse.setErrmsg("ok");

            return wechatQRCodeResponse;
        }

        @Override
        protected void writeInternal(GetWechatQRCodeResponse appGetWechatQRCodeResponse, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
            StreamUtils.copy(appGetWechatQRCodeResponse.getBuffer(), outputMessage.getBody());
        }
    }
}
